//
//  ZJTabBar.m
//  zjzb
//
//  Created by Mac on 2017/3/24.
//  Copyright © 2017年 Mac. All rights reserved.
//

#import "ZJTabBar.h"

@interface ZJTabBar()
@property (nonatomic, strong) NSArray * datalist;

//记录上一次点击的按钮

@property(nonatomic,weak)UIButton *lastButton;

@property (nonatomic, strong) UIImageView * tabbgView;

@end

@implementation ZJTabBar

- (UIImageView *)tabbgView {
    
    if (!_tabbgView) {
        _tabbgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"global_tab_bg"]];
    }
    return _tabbgView;
}

- (NSArray *)datalist {
    
    if (!_datalist) {
        _datalist = @[@"tabbar_home",@"tabbar_room",@"tabbar_me"];
    }
    return _datalist;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setupUI];
        
    }
    return self;
}

-(void)setupUI {
    
    //添加界面的背景
     [self addSubview:self.tabbgView];
    
    for (NSInteger i = 0; i < self.datalist.count; i++) {
        
        NSString *name = self.datalist[i];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [button setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_sel",name]] forState:UIControlStateSelected];
    
        button.tag = 1000+i;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //初始化第一个按钮已经点击
        if (i==0) {
            button.selected = YES;
            
            self.lastButton = button;
        }
        [self addSubview:button];
        
    }
    
    
}
//进行子控件的设置
-(void)layoutSubviews{
    [super layoutSubviews];
    
    self.tabbgView.frame = self.bounds;
    CGFloat width = self.bounds.size.width/self.datalist.count;
    for (int i = 0; i < [self subviews].count; i++) {
        UIView *view = [self subviews][i];
        if ([view isKindOfClass:[UIButton class]]) {            
            view.frame = CGRectMake((view.tag-1000)*width, 0, width, self.bounds.size.height);
        }
    }
}

//按钮的点击事件
-(void)buttonClick:(UIButton *)button {
    
    if (self.block) {
        self.block(self,button.tag);
    }

    if ([self.delegate respondsToSelector:@selector(zjtabbar:WithIndex:)]) {
        [self.delegate zjtabbar:self WithIndex:button.tag];
    }
    
    button.selected = YES;
    self.lastButton.selected = NO;
    self.lastButton = button;
    //设置动画
    [UIView animateWithDuration:0.2 animations:^{
        //将button扩大1.2倍
        button.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            //恢复原始状态
            button.transform = CGAffineTransformIdentity;
        }];
    }];
 
}

@end
